package com.fwh.web.controller;

import cn.hutool.json.JSONArray;
import jdk.nashorn.internal.codegen.CompilerConstants;
import jdk.nashorn.internal.ir.RuntimeNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.util.HttpURLConnection;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

/**
 * instagram 登录验证
 *
 * @author fwh
 * @email fuwenhao594@163.com
 * @date 2019/7/19 下午4:01
 */
@Slf4j
public class InstagramController extends HttpServlet {
//    public static void main(String[] args) {
//        String clientID = "630c8d857d6448e6bb44b05954d11b74";
//        String clientSecret = "925b70ea12b644a4bbe3353568c4b0e7";
//        String redirectURI = "http://fuwenhao.club/";
//        String code = "code";
//        String token = "token";
//        try {
//            //https://api.instagram.com/oauth/authorize/?client_id=630c8d857d6448e6bb44b05954d11b74&redirect_uri=http://fuwenhao.club/&response_type=token
//            String httpurl = "https://api.instagram.com/oauth/authorize?"
//                    + "client_id=" + clientID
//                    + "&redirect_uri=" + redirectURI
//                    + "&response_type=" + token;
//
//            URL url = new URL(httpurl);
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            conn.setRequestMethod("POST");
//            String urlParameters = "client_id=" + clientID
//                    + "&client_secret=" + clientSecret
//                    + "&grant_type=authorization_code"
//                    + "&redirect_uri=" + redirectURI
//                    + "&code=" + code;
//
//            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            conn.setRequestProperty("charset", "utf-8");
//            conn.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
//
//            conn.setDoOutput(true);
//            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
//            wr.writeBytes(urlParameters);
//            wr.flush();
//            wr.close();
//
//            BufferedReader in = new BufferedReader(new InputStreamReader(
//                    conn.getInputStream()));
//            System.out.println(in);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//    }


//    public static void main(String[] args) {
//            //先从缓存读取
//            JSONArray array = CacheKit.get("userPhoto", username);
//            if (array != null)
//                return array;
//            //1.获取userId
//            String url = "https://www.instagram.com/" + username + "/?__a=1";
//            //由于墙外地址，使用代理（请自行修改）
//            OkHttpClient okHttpClient = new OkHttpClient().newBuilder().proxy((new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8118)))).build();
//            RuntimeNode.Request request = new RuntimeNode.Request.Builder().url(url).build();
//            CompilerConstants.Call call = okHttpClient.newCall(request);
//            try {
//                Response response = call.execute();
//                JSONObject jsonObject = JSONObject.parseObject(response.body().string());
//                String userId = ((JSONObject) jsonObject.get("user")).get("id").toString();
//                //System.out.println(jsonObject.toJSONString());
//                //2.获取内容
//                String contentUrl = "https://www.instagram.com/graphql/query/?query_id=17880160963012870&id=" + userId + "&first=999";
//                request = new RuntimeNode.Request.Builder().url(contentUrl).build();
//                response = okHttpClient.newCall(request).execute();
//                jsonObject = JSONObject.parseObject(response.body().string());
//                //System.out.println(jsonObject.toJSONString());
//                //data.user.edge_owner_to_timeline_media.edges
//                array = jsonObject
//                        .getJSONObject("data")
//                        .getJSONObject("user")
//                        .getJSONObject("edge_owner_to_timeline_media")
//                        .getJSONArray("edges");
//                //设置缓存（k-username,V-图文）
//                CacheKit.put("userPhoto", username, array);
//                return array;
//            } catch (Exception e) {
//                e.printStackTrace();
//                return null;
//            }
//    }






    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession(true);
//        String clientID = (String) session.getAttribute("client_id");
//        String clientSecret = (String) session.getAttribute("client_secret");
//        String redirectURI = (String) session.getAttribute("redirect_uri");
//        String code = request.getParameter("code");
        String clientID = "630c8d857d6448e6bb44b05954d11b74";
        String clientSecret = "925b70ea12b644a4bbe3353568c4b0e7";
        String redirectURI = "http://fuwenhao.club/";
//        String code = request.getParameter("token");
        String code = request.getParameter("code");
        JSONObject profile = getTokenContent(clientID, clientSecret, redirectURI, code);
    }

    public JSONObject getTokenContent(String clientID, String clientSecret, String redirectURI, String code) {
        try {

            String httpurl = "https://api.instagram.com/oauth/access_token?"
                    + "client_id=" + clientID
                    + "&client_secret=" + clientSecret
                    + "&grant_type=authorization_code"
                    + "&redirect_uri=" + redirectURI
                    + "&code=" + code;

            URL url = new URL(httpurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

            String urlParameters = "client_id=" + clientID
                    + "&client_secret=" + clientSecret
                    + "&grant_type=authorization_code"
                    + "&redirect_uri=" + redirectURI
                    + "&code=" + code;

            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("charset", "utf-8");
            conn.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

            conn.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
//            return JSONObject;
//            return getJSONFromBufferRd(in);

        } catch (Exception e) {
            log.error("yic{}", e);
        }
        return null;
    }
}
